package com.fy.common.config;

import lombok.Data;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

@Data
@Configuration
@ConfigurationProperties(prefix = "redisson")
@ConditionalOnProperty(name = "spring.redis.enabled", havingValue = "true", matchIfMissing = false)
public class RedissonConfig {

    private String host;

    private String password;

    private String port;

    private int timeout;

    private static String ADDRESS_PREFIX = "redis://";

    private static final Logger log = LoggerFactory.getLogger(RedissonConfig.class);

    private SingleServerConfig singleServerConfig;

    /**
     * 自动装配
     *
     */
    @Bean
    public RedissonClient redisson() {
        try {
            Config config = new Config();
            SingleServerConfig serverConfig = config.useSingleServer()
                    .setAddress(singleServerConfig.getAddress())
                    .setDatabase(singleServerConfig.getDatabase())
                    .setTimeout(singleServerConfig.getTimeout())
                    .setConnectionMinimumIdleSize(singleServerConfig.getConnectionMinimumIdleSize())
                    .setConnectionPoolSize(singleServerConfig.getConnectionPoolSize());

            if (StringUtils.hasText(singleServerConfig.getPassword())) {
                serverConfig.setPassword(singleServerConfig.getPassword());
            }

            return Redisson.create(config);
        } catch (Exception e) {
            log.error("Redis连接失败:", e);
            throw e;
        }
    }
}